package api;

import dao.User;
import dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取请求中的用户名和密码
        //    给请求对象设置字符集, 保证说请求中的 username 或者 password 是中文, 也能正确处理.
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String enteredCaptcha = req.getParameter("captcha");

        HttpSession session = req.getSession(true);
        String storedCaptcha = (String) session.getAttribute("captcha");

        if (enteredCaptcha == null || !enteredCaptcha.equals(storedCaptcha)) {
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("验证码有错误");
            System.out.println(storedCaptcha);
            return;
        }
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            // 当前提交的用户名密码有误!
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前传过来的 username 或者 password 为空");
            return;
        }
        // 2. 和数据库进行验证. 看当前这样的用户名和密码是否匹配.
        UserDao userDao = new UserDao();
        User user = userDao.getUserByName(username);
        if (user == null) {
            // 当前提交的用户名密码有误!
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您的用户名或者密码错误!");
            return;
        }
        if (!password.equals(user.getPassword())) {
            // 当前提交的用户名密码有误!
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("您的用户名或者密码错误!");
            return;
        }
        // 3. 创建会话
        // 把当前登录的用户信息保存到 session 中, 方便后续进行获取.
        session.setAttribute("user", user);
        // 4. 跳转到博客列表页.
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 会话不存在, 就认为是未登录.
        HttpSession session = req.getSession(false);
        if (session == null) {
            // 未登录
            resp.setStatus(403);
            return;
        }
        // 不仅仅是看 session 对象本身, 还需要看 user 对象存在. (为了后面实现 "退出登录" 功能)
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            return;
        }
        // 返回 200 表示已经登陆.
        resp.setStatus(200);
    }
}